<template>
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                >
                </el-tab-pane>
                <el-tab-pane
                    label="结算清单"
                    name="contractList"
                    :disabled="clickTabFlag"
                >
                </el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="attach"
                    :disabled="clickTabFlag"
                >
                </el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form
                                :model="formData"
                                :label-width="formLabelWidth"
                                :rules="rulesBase"
                                ref="rulesBase"
                                class="demo-ruleForm"
                            >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="结算编号：" prop="billNo">
                                            <span>{{
                                                formData.billNo
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="单据机构：" prop="orgName">
                                            <span>{{ formData.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="业务类型：" prop="businessType">
                                            <el-select v-model="formData.businessType" placeholder="请选择">
                                                <el-option
                                                v-for="item in ywlx"
                                                :key="item.id"
                                                :label="item.name"
                                                :value="item.id">
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="源单编号：">
                                        {{formData.sourceNo}}
                                        <span class="a"
                                        @click="seeSourceOrder">查看</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="结算单位：" prop="settleOrgName">
                                            <el-input type="text" v-model="formData.settleOrgName">
                                            </el-input>
                                            <el-button @click="xzzcdb" class="btn-blue" style="margin-left:5px">选择周材调拔</el-button>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="录入人员：" prop="inputName">
                                            <span>{{ formData.inputName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="税率%：" prop="taxRate">
                                            <el-input v-model="formData.taxRate"
                                            @change="taxRateEvent"
                                            ></el-input>
                                            <!-- <span>{{
                                                formData.taxRate
                                            }}</span> -->
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="结算日期：" prop="settleDate">
                                             <el-date-picker v-model="formData.settleDate" type="date" placeholder="选择日期" :clearable="false">
                                                </el-date-picker>

                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="税额(元)：">
                                            <!-- <span>{{
                                                formData.taxAmount
                                            }}</span> -->
                                            <el-input v-model="formData.taxAmount"
                                            ></el-input>
                                            <!-- <span>{{shuie}}</span> -->
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="调拔人员：">
                                            <span>{{ formData.pullPeopleName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="结算金额：">
                                            <!-- <span>{{
                                                formData.settleAmount jiesuanjine
                                            }}</span> -->
                                            <span>
                                                {{jiesuanjine}}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                            <el-form-item label="接收人员：" >
                                            {{formData.receivePeopleName}}
                                            </el-form-item>
                                        </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="税价合计：">
                                            <!-- <span>{{formData.totalPrice}}</span> -->
                                          <span>{{shuijiaheji}}</span>
                                        </el-form-item>
                                    </el-col>
                                      <el-col :span="12">
                                        <el-form-item label="币种：">
                                        <span>{{formData.currency}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="累计结算金额：">
                                            <span>{{
                                                formData.totalSettleAmount
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="本位币：">
                                            <span>{{ formData.baseCurName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="传财务共享：">
                                            <span>
                                            {{shareLable(formData.isSharing)}}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                          <span>{{ state.find(x=>x.value === formData.state)?state.find(x=>x.value === formData.state).label:'' }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="结算金额(本位币)：">
                                            <span>{{
                                                formData.baseSettleAmount
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                        <el-col :span="24">
                                            <el-form-item label="备注：">
                                               <el-input type="textarea" :rows="2" laceholder="请输入内容" v-model="formData.remarks"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                            </el-form>
                        </div>
                    </div>

                    <!-- 结算清单 审核可以修改-->
                    <div id="contractListCon" class="con">
                        <div class="tabs-title" id="contractList">结算明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button
                                            size="small"
                                            style="background: rgb(75, 178, 255); color: #fff"
                                            @click="xzzcdb"
                                            >选择物资</el-button
                                        >
                                        <el-button
                                            size="small"
                                            type="danger"
                                            @click="dellwz"
                                            >删除</el-button
                                        >
                                    </div>
                                </div>
                            </div>
                            <el-table
                            ref="jsdwdataTable"
                            :header-cell-style="{ textAlign: 'center' }"
                            :cell-style="{ textAlign: 'center' }"
                            :data.sync="jsdwdata"
                            border
                            style="width: 100%; "
                            @selection-change="planTableSelect"
                            :row-class-name="tableRowClassName"
                            :tree-props="{
                                children: 'children',
                                hasChildren: 'hasChildren',
                                }"
                            default-expand-all
                            row-key="uuid"
                            v-sortTable="{ 'tableData': jsdwdata, '_this': this, 'ref': 'jsdwdataTable' }"
                                >
                                 <el-table-column type="selection" width="55">
                                 </el-table-column>
                                <el-table-column prop="materialClassName" label="物资类别" width="150">
                                </el-table-column>
                                <el-table-column prop="materialName" label="物资名称" >
                                </el-table-column>
                                <el-table-column prop="spec" label="规格" width="150">
                                </el-table-column>
                                <el-table-column prop="texture" label="材质" width="150">
                                </el-table-column>
                                <el-table-column prop="unit" label="单位" width="100">
                                </el-table-column>

                                <el-table-column
                                    prop="allocationQuantity"
                                    label="调拔数量"
                                    min-width="150"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.allocationQuantity }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="notSettleQuantity"
                                    label="未结算数量"
                                    min-width="150"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.notSettleQuantity }}</span>
                                    </template>
                                </el-table-column>
                                <!-- <el-table-column
                                    prop="settlementAmount"
                                    label="未摊销单价（元）"
                                    min-width="150"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.settlementAmount }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="currentTotalProportion"
                                    label="未摊销金额（元）"
                                    min-width="150"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.currentTotalProportion }}</span>
                                    </template>
                                </el-table-column> -->
                                <el-table-column
                                    prop="currentTotalAmount"
                                    label="结算数量"
                                    min-width="150"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-if="row.billId" v-model="row.settleQuantity" @input="change11(row)"></el-input>
                                        <!-- <span>{{ row.settleQuantity }}</span> -->
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="内部结算单价（元）"
                                    min-width="150"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.internalSettlementUnitPrice }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="实际采购单价（元）"
                                    min-width="150"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.actualPurchaseUnitPrice }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="结算金额（元）"
                                    min-width="150"
                                >
                                    <template slot-scope="{ row }">
                                        <el-input v-if="row.billId || row.billId == ''" v-model="row.settleAmount" @input="change11(row)"></el-input>
                                        <!-- <span>{{ row.settleAmount }}</span> -->
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    label="价差（元）"
                                    min-width="150"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.priceDifference }}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                   <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp
                            :relationId="attachId"
                            bucketName="subcontract"
                        />
                    </div>

                     <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <ExaHistory :billType="6097" :tableData="historyData" @getAuditHistory ="getHistoryData"></ExaHistory>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <el-button
                    type="primary"
                    style="background: #2e61d7"
                    v-if="
                    formData.state == 2 || formData.state == '2'
                "
                    @click="chonghongdan"
                    >冲红单</el-button
                >
            <exaButtons :auditState="auditState" @exas="exas" :state="formData.state - 0" :founderId="formData.founderId"></exaButtons>
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>

    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapState, mapMutations } from 'vuex'
import AttachComp from '@/components/common/attachIndex'
import $ from 'jquery'
// import { showLoading, hideLoading, throttle } from '@/utils/common'
import ExaHistory from '@/components/common/exaHistory.vue'
import {   getBondList, updateBond, updateBondList } from '@/api/settlementManagement/gongchengjieshuan/baozhengjin.js'
// import {  flowCommit } from '@/api/settlementManagement/gongchengjieshuan/jiakoukuan.js'
import auditRequest from '@/api/settlementManagement/peripheralMaterial/peripheralMaterial.js'
import exaButtons from '@/components/common/exaButtons'
import {
    showLoading,
    throttle,
    hideLoading,
    openAppClient,
    selectDataClient,
    getUuid
} from '@/utils/common'
export default {
    data () {
        return {
            //基本信息表单数据
            jsdwdata: [],
            auditState: {},
            ywlx: [
                {
                    id: 2,
                    name: '周材调拨单'
                }
            ],
            father: {},
            rulesBase: {
                // 结算编号 billNo 单据机构orgName 业务类型businessType 源单编号sourceNo 结算单位settleOrgName 录入人员inputName 税率%taxRate  结算日期settleDate
                billNo: [
                    { required: true, message: '结算编号不能为空', trigger: 'change' }
                ],
                orgName: [
                    { required: true, message: '机构不能为空', trigger: 'change' }
                ],
                businessType: [
                    { required: true, message: '业务类型不能为空', trigger: 'change' }
                ],
                sourceNo: [
                    { required: true, message: '源单编号不能为空', trigger: 'change' }
                ],
                taxRate: [
                    { required: true, message: '税率不能为空', trigger: 'change' }
                ],
                settleDate: [
                    { required: true, message: '结算日期不能为空', trigger: 'change' }
                ],
                settlementDate: [
                    { required: true, message: '结算日期不能为空', trigger: 'change' }
                ],
                settleOrgName: [
                    { required: true, message: '结算单位不能为空', trigger: 'change' }
                ],
            },
            formData: {
                businessType: 2,
                'amount': 0,
                'baseCurAmount': 0,
                'baseCurId': '',
                'baseCurName': '',
                'baseCurRate': 0,
                'billId': '',
                'billNo': '',
                'contractId': '',
                'contractName': '',
                'currency': '',
                'currencyId': '',
                'easId': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'outsourcerId': '',
                'outsourcerName': '',
                'period': 0,
                'remarks': '',
                'rmbAmount': 0,
                'rmbId': '',
                'rmbName': '',
                'rmbRate': 0,
                'settlementDate': '',
                'state': '',
                'workId': '',
                'totalPrice': 0,
                taxRate: 0
            },
            isFatherNoHas: true,
            formLabelWidth: '195px',
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
 	        winEvent: {},
            errorList: [], //控制导航栏感叹号的显示
            billid: this.$route.query.billid,
            disabled: false, //是否禁止
            // auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 6097
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 6097,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: ''
            },
            errorServiceMsg: [],
            showBaseCurName: true,
            historyData: [], //审核历史数据
            settlementList: [], //结算列表
            errorBondMsg: [], //清单错误信息
            previousTotalAmount: 0, //上期末金额
        }
    },
    components: {
        AttachComp,
        ExaHistory,
        exaButtons
    },
    async created () {

        this.billId = this.$route.query.billid
        this.auditState = await auditRequest.getanniu({
            billId: this.$route.query.billid,
            billType: 6097
        })
        console.log(this.auditState, 'ooo')
        this.user = JSON.parse(localStorage.getItem('vuex'))
        this.init()

    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
        // 保存所有tabName
        const arr = [
            'baseInfo',
            'contractList',
            'attach',
            'auditHistory'
        ]
        this.tabArr = arr
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
        if(this.$route.query.name) {
            setTimeout(()=>{
                this.onChangeTab({
                    name: this.$route.query.name
                })
                this.tabsName = this.$route.query.name
            }, 200)
        }
    },

    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    computed: {
        ...mapState({
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            state: state => state.equip.equipData.state, //通用流程状态
        }),
        //传输财务共享
        shareLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.shareFrom
                const obj = state.find(x=>x.value === param)
                return (obj ?  obj.label :  '')
            }
        },
        shuie () {
            // formData.taxAmount
            return (this.formData.taxRate - 0) * this.jiesuanjine / 100 - 0
        },
        jiesuanjine () {
            // settleQuantity结算数量
            // internalSettlementUnitPrice内部结算单价（元）
            // actualPurchaseUnitPrice 实际采购单价（元）
            // settleAmount结算金额（元）
            // priceDifference价差（元）
            let num = 0
            for(let i = 0 ; i < this.jsdwdata.length ; i++) {
                for(let j = 0 ; j < this.jsdwdata[i].children.length ; j++) {
                    num += this.jsdwdata[i].children[j].settleAmount - 0 || 0
                }
            }
            return num.toFixed(2) - 0
        },
        shuijiaheji () {
            const val = Number(this.formData.taxAmount) + Number(this.jiesuanjine)
            return val ? val.toFixed(2) * 1 : 0
        },

        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.$route.query.billid
        },
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        // shuijiaheji formData.totalSettleAmount
        shuijiaheji (qzx) {
            this.formData.totalSettleAmount = qzx + this.previousTotalAmount
        },
        //监听截止上期末
        previousTotalAmount: {
            handler (newVal) {
                if(typeof newVal == 'number') {
                    //更新累计结算金额
                    this.formData.totalSettleAmount = (this.shuijiaheji + (newVal || 0)).toFixed(2) * 1
                }
            }
        },
    },
    methods: {
        ...mapMutations(['setAuditParams']),
        ...mapMutations(['setSelectedInfo']),
        change11 (row) {
            // settleQuantity结算数量
            // internalSettlementUnitPrice内部结算单价（元）
            // actualPurchaseUnitPrice 实际采购单价（元）
            // settleAmount结算金额（元）
            // priceDifference价差（元）
            if((row.settleQuantity - 0) > 0 && (row.settleAmount - 0) > 0) {
                row.internalSettlementUnitPrice = (row.settleAmount / row.settleQuantity).toFixed(2) - 0
                row.priceDifference = ((row.settleQuantity - 0) * ((row.internalSettlementUnitPrice - 0) - (row.actualPurchaseUnitPrice - 0))).toFixed(2) - 0
            }
            this.formData.taxAmount = (this.jiesuanjine * (this.formData.taxRate / 100)).toFixed(2) * 1
        },
        dellwz () {
            // alert('111')
            this.clientPop('info', '确认删除这' + this.planSelect.length + '条数据吗？', this.deljkk3)
        },
        deljkk3 () {
            console.log('222', this.jsdwdata)
            // this.jsdwdata[i]
            for(let i = 0 ; i < this.jsdwdata.length; i++) {
                for(let j = 0; j < this.jsdwdata[i].children.length ; j++) {
                    for(let h = 0 ; h < this.planSelect.length ; h++) {
                        if(this.jsdwdata[i].children[j].uuid ==  this.planSelect[h].uuid) {
                            this.jsdwdata[i].children[j].changeType = -1
                        }
                    }
                }
            }
            this.$refs.multipleTable1.clearSelection()

            // for(let i = 0 ; i < this.jsdwdata.length; i++) {
            //     if(this.jsdwdata[i]) {
            //         for(let j = 0 ; j < this.jsdwdata[i].children.length ; i++) {
            //             for(let h = 0 ; h < this.planSelect.length ; h++) {
            //                 if(this.jsdwdata[i].children[j].uuid ==  this.planSelect[h].uuid) {
            //                     console.log('顶顶顶顶')
            //                     this.jsdwdata[i].children[j].changeType = -1
            //                     console.log('dddddddd')
            //                 }
            //             }
            //         }
            //     }
            // }
            // console.log('333')
            // this.$refs.multipleTable1.clearSelection()
        },
        async exas (arg) {
            console.log(arg)
            if (arg === 'submit') {
                console.log('2') // 保存所有数据
                await this.submit()
            } else if (arg === 'submitCommit') {
                console.log('2') // 保存并提交
                await this.submitCommit()
            } else if (arg === 'audit') {
                console.log('3') // 审核
                await this.shenhe()
            } else if (arg === 'undoAudit') {
                await this.nullify() // 撤销审核
            } else if (arg === 'nullify') {
                console.log('5') // 作废(
                await this.zuofei()
            } else if (arg === 'deleteData') {
                console.log('6') // 删除
                await this.shanchu1()
            }
        },
        shanchu1 () {
            this.clientPop('info', '确定要删除吗？数据删除后不可恢复，请谨慎操作', ()=>{
                auditRequest.deldbjs({ id: this.billId })
                    .then(()=>{
                        this.clientPop('suc', '删除成功')
                        this.$router.replace('/peripheralMaterialList')
                    })
            })

        },
        async xzzcdb () {
            selectDataClient({
                SelectServiceToken: '/turnover/allocation/getSettleDtl', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({
                    keyWord: '',
                    orgId: this.user.userInfo.orgInfo.orgId,
                    // orgId: '1439990097591140358',
                    parentId: '0',
                }),    // 接口参数(name为模拟参数)
                Title: '选择结算明细' // 标题
            }).then(async val => {
                let res = val[0] //默认用户选择了第一个 模拟弹窗
                for(let i = 0 ; i < val.length ; i++) {
                    if(val[i].parentId != '0') {
                        res = val[i]
                    }
                }
                this.$set(this.formData, 'sourceNo', res.billNo) //源单编号
                this.$set(this.formData, 'sourceId', res.billId) //源单id
                this.$set(this.formData, 'settleOrgName', res.transferOrgName) //结算单位名称
                this.$set(this.formData, 'settleOrgId', res.transferOrgId) //结算单位 id

                this.$set(this.formData, 'pullPeopleName', res.pullPeopleName) //调拔人员
                this.$set(this.formData, 'pullPeopleId', res.pullPeopleId) //调拔人员id

                this.$set(this.formData, 'receivePeopleName', res.receivePeopleName) //接收人员
                this.$set(this.formData, 'receivePeopleId', res.receivePeopleId) //接收人员id

                this.$set(this.formData, 'currency', res.currency) //币种
                this.$set(this.formData, 'currencyId', res.currencyId) //币种id
                this.$set(this.formData, 'taxRate', res.taxRate) //税率

                //结算明细 ↓
                res = []
                for(let i = 0 ; i < val.length ; i++) {
                    if( val[i].parentId != '0' && val[i].parentId != 0) {
                        res.push(val[i])
                    }
                }
                const mapObj1 = {}
                let arr1 = []
                res.forEach(e => {
                    const children = []
                    e.materialClassNameArr = e.materialClassName.split('/')
                    e.materialClassIdArr = e.materialClassId.split('/')
                    let obj
                    const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                    const topClassName = e.materialClassNameArr.splice(0, 1).toString()
                    if (!mapObj1[topClassId]) {
                        obj = {
                            topClassId,
                            topClassName,
                            customId: topClassId,
                            materialClassId: topClassId,
                            materialClassName: topClassName,
                            uuid: getUuid(),
                            totalAmount: null,
                            totalQuantity: null,
                        }
                        //这里需要改成push多个对象   还没改
                        arr1.push(obj)
                        mapObj1[topClassId] = obj
                    } else {
                        obj = mapObj1[topClassId]
                    }
                    // sourceDtlId
                    children.push({
                    // settledAmount金额 settledQuantity结算数量 settledPrice单价 taxDifference税额差价
                        uuid: getUuid(),
                        billId: this.billid || '',
                        billNo: this.formData.billNo || '',
                        customId: getUuid(),
                        // warehouse: e.warehouse,
                        // unsettledQuantity: (e.unsettledQuantity - 0 ) + 2, //未结算数量
                        acceptedQuantity: null, //已验收数量
                        changeType: 999,
                        dtlId: '', //加工收料明细id
                        materialClassId: e.materialClassIdArr.join('/'), //物资类别id(
                        materialClassName: e.materialClassNameArr.join('/'), //物资类别名称
                        materialId: e.materialId, //物资id
                        materialName: e.materialName, //物资名称
                        settledPrice: 0, //单价
                        // quantity: e.surplusQuantity, //数量
                        sourceDtlId: e.dtlId, //源单明细id
                        spec: e.spec, //规格型号
                        texture: e.texture, //材质
                        unit: e.unit, //计量单位
                        // warehouseName: e.warehouseName\t, //仓库名称
                        settledQuantity: 0, //结算数量
                        settledAmount: 0, //金额
                        // acceptanceAmount: e.acceptanceAmount, //验收金额
                        difference: 0, //差额
                        // taxDifference: 0, //税价差额
                        // quantity: e.unsettledQuantity, //结算数量 带入未结算数量
                        price: 0,
                        amount: 0,
                        taxDifference: 0, //税价差额
                        allocationQuantity: e.quantity || 0, //调拔数量
                        notSettleQuantity: e.notSettleQantity || 0, //未结算数量
                        notAmortizationPrice: 0, //先不管 未摊销单价
                        notAmortizationAmount: 0, // 先不管 未摊销金额
                        settleQuantity: e.notSettleQantity || 0, //结算数量
                        internalSettlementUnitPrice: 0, //内部结算单价
                        actualPurchaseUnitPrice: e.price, //实际采购单价
                        settleAmount: 0, //结算金额
                        priceDifference: 0//价差

                        // actualPurchaseUnitPrice

                    })
                    obj.children = !obj.children
                        ? children
                        : obj.children.concat(children)
                    obj.children = this.uniqueArray(obj.children, 'customId')
                })
                this.jsdwdata = JSON.parse(JSON.stringify(arr1))
                //获取截止上期末累计结算金额
                auditRequest.getPrevAmount({ sourceId: this.formData.sourceId })
                    .then(res=>{
                        if(typeof res == 'number') {
                            this.previousTotalAmount = res
                        }else {
                            this.previousTotalAmount = 0
                        }
                    })
            })
        },
        //明细数据汇总方法
        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('auditHistory')) {
                    const lastConHeight =
                        document.getElementById('auditHistory').offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x=>x === name)
            if(index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        async chonghongdan () {
            await auditRequest.chonghongdan2({ id: this.billId })
            this.clientPop('suc', '冲红单成功')
            this.$router.replace('/peripheralMateriallist')
        },
        async init () {
            // showLoading()
            await this.getBasic()
            this.getHistoryData()
            // this.getBasic().then(()=>{
            //     this.getHistoryData()
            // }).finality(()=>{
            //     hideLoading()
            // })
        },
        //获取基本信息
        async getBasic () {
            this.formData = await auditRequest.getjbxx({ id: this.billid })
            //获取截止上期末累计结算金额
            auditRequest.getPrevAmount({ sourceId: this.formData.sourceId })
                .then(res=>{
                    if(typeof res == 'number') {
                        this.previousTotalAmount = res
                    }else {
                        this.previousTotalAmount = 0
                    }
                })
            //明细
            const data = await auditRequest.getjsmx({ billId: this.billid })
            for(let i = 0 ; i < data.length; i++) {
                data[i].uuid = getUuid()
                for(let j = 0 ; j < data[i].children.length; j++) {
                    data[i].children[j].uuid = getUuid()
                }
            }
            this.jsdwdata = data
        },
        //获取结算列表
        getSettlementList () {
            getBondList({ id: this.billid }).then(res=>{
                this.settlementList = res
            })
        },
        //获取审核历史
        async getHistoryData () {
            this.historyData = await auditRequest.getshenhelishi(this.auditParams)
        },
        async nullify () {
            console.log('撤回')
            await auditRequest.chehui({ billId: this.billId, billType: 6097 })
            this.clientPop('suc', '撤回成功')
            this.$router.replace('/peripheralMaterialList')
        },
        zuofei () {
            // showLoading()
            // hideLoading()
            this.setAuditParams(this.nullifyParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                // this.setSelectedInfo(auditParams)
                // // 客户端弹窗预览结果
                // // 参数依次为: 打开页面地址、标题、回调函数
                // openAppClient('/showSelectedData', '选择结果', function () {
                //     // alert('关闭后回调')
                // })
                showLoading()
                auditRequest
                    .zuofei(auditParams)
                    .then(() => {
                        this.clientPop('suc', '作废成功', this.handleClose)
                    })
                    .finally(() => {
                        hideLoading()
                    })
            })
        },
        planTableSelect (selection) {
            console.log('变化了 ', selection)
            this.planSelect = selection
        },
        shenhe () {
            console.log('审核')
            // auditRequest.tijiaoshenhe({
            //     billId: this.billId,
            //     billType: 6097,
            //     isPass: true,
            //     isShareInAudit: false,
            //     opinion: '111'

            // })
            openAppClient('/exaDialog', '填写审核意见',  ()=> {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                // 将审核意见赋值给参数传给后端
                auditRequest.faqishenhe({
                    billId: this.$route.query.billid,
                    billType: 6097,
                    isPass: auditParams.isPass,
                    isShareInAudit: false,
                    opinion: auditParams.opinion

                }).then(() => {
                    this.clientPop('suc', '审核成功')
                    this.$router.replace('/peripheralMaterialList')
                }).catch(()=>{
                    this.clientPop('suc', '审核失败')
                })

            })
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                this.$refs.rulesBase.validate(valid => {
                    if (valid) {
                        updateBond(this.formData).then(() => {
                            this.clearError('baseInfo')
                            resolve()
                            this.getBasic()
                        }).catch(err=>{
                            reject(err)
                            this.setError('baseInfo')
                        })
                    } else {
                        this.setError('baseInfo')
                        reject('基本信息错误')
                    }
                })
            })
        },
        //保存清单
        saveSettlementList (isComit = false) {
            return new Promise((resolve, reject)=>{
                let settlementList = []
                settlementList = [...this.settlementList]
                if(isComit) {
                    const filterData = settlementList.filter(x=>x.changeType !== -1)
                    if(filterData.length === 0) {
                        this.setError('contractList')
                        reject('必须引入清单')
                        return
                    }
                    else{
                        this.errorBondMsg = []
                        filterData.forEach(item=>{
                            !item.unit ? this.setErrorBondMsg('请选择单位') : ''
                            !item.placeOfDeparture ? this.setErrorBondMsg('请填写出发地') : ''
                            !item.destination ? this.setErrorBondMsg('请填写目的地') : ''
                            !item.mileage ? this.setErrorBondMsg('请选写里程') : ''
                            !item.quantity ? this.setErrorBondMsg('请填写数量') : ''
                            !item.unitPrice ? this.setErrorBondMsg('请填写单价') : ''
                            if(item.quantity > item.oriQuantity  && item.oriQuantity)this.setErrorBondMsg('不能超过招标的数量')

                        })
                        if(this.errorBondMsg.length > 0) {
                            this.setError('contractList')
                            reject('合同清单错误')
                            return
                        }else{
                            this.clearError('contractList')
                        }
                    }

                }else{
                    if(settlementList.length === 0) {
                        resolve()
                        return
                    }
                }
                const filterData = settlementList.filter(x=>x.changeType !== 0)

                const newListAll =  filterData.map(x=>{
                    const obj = {
                        'billId': '',
                        'changeType': 0,
                        'contractAmount': 0,
                        'contractProportion': 0,
                        'currentTotalAmount': 0,
                        'currentTotalProportion': 0,
                        'dtlId': '',
                        'itemId': '',
                        'itemName': '',
                        'itemNo': '',
                        'previousTotalAmount': 0,
                        'previousTotalProportion': 0,
                        'settlementAmount': 0,
                        'settlementProportion': 0
                    }
                    for(let key in obj) {
                        obj[key] = x[key]
                    }
                    return obj
                })
                if(newListAll.length === 0) {
                    resolve()
                    return false
                }
                updateBondList(newListAll).then(()=>{
                    this.clearError('contractList')
                    resolve()
                    this.getSettlementList()
                }).catch(err=>{
                    this.setError('contractList')
                    reject(err)
                })
            })

        },
        setErrorBondMsg (msg) {
            let index = this.errorBondMsg.findIndex(x=>x === msg)
            if(index === -1) {
                this.errorBondMsg.push(msg)
            }
        },
        //先保存合同清单 再保存基本信息
        saveMianList (isComit = false) {
            return new Promise((resolve, reject)=>{
                this.saveSettlementList(isComit).then(()=>{
                    this.updateBaseInfo().then(()=>{
                        resolve()
                    }).catch(err=>{
                        reject(err)
                    })
                }).catch(err=>{
                    reject(err)
                })

            })
        },
        //保存全部数据
        saveAll () {
            showLoading()
            this.errorList = []
            Promise.all([
                this.saveMianList(),
            ])
                .then(() => {
                    this.$store.commit('contract/setMaterialList', [])
                    hideLoading()
                    this.clientPop('suc', '保存成功')
                })
                .catch(err => {
                    console.log('errMsg：', err)
                    this.clientPop('err', '保存失败', ()=>{
                        this.scorllError()
                    })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        async thesubimt1 () {
            // submit taxAmount
            // this.setSelectedInfo(this.formData)
            //
            // 参数依次为: 打开页面地址、标题、回调函数
            // openAppClient('/showSelectedData', '看看bug', function () {
            //     // alert('关闭后回调')
            // })
            showLoading()
            //更新基本信息字段
            //结算金额
            this.formData.settleAmount = this.jiesuanjine
            //税价合计
            this.formData.totalPrice = this.shuijiaheji
            //累计结算金额
            this.formData.totalSettleAmount = this.shuijiaheji
            await auditRequest.setjbxx({ ...this.formData })
            for(let i = 0 ; i < this.jsdwdata.length ; i++) {
                for(let j = 0 ;j < this.jsdwdata[i].children.length ; j++) {
                    if(this.jsdwdata[i].children[j].changeType != -1) {
                        if(this.jsdwdata[i].children[j].changeType == 999) {
                            this.jsdwdata[i].children[j].changeType = 1
                        }else if(this.jsdwdata[i].children[j].changeType == 0 ) {
                            this.jsdwdata[i].children[j].changeType = 2
                        }
                    }
                }
            }
            await auditRequest.updatejxmx(this.jsdwdata)
            await auditRequest.tijiaoshenhe({
                'billId': this.$route.query.billid,
                'billType': 6097,
                'freeNextUnitIndex': 0,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': ''
            })
            hideLoading()
            this.clientPop('suc', '提交成功')
            this.$router.replace('/peripheralMaterialList')
        },
        //保存并提交
        submitCommit () {
            this.$refs.rulesBase.validate(valid => {
                console.log('gg', valid)
                if (valid) {
                    this.thesubimt1()
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        async thesubimt0 () {
            // this.setSelectedInfo(this.formData)
            // // // 客户端弹窗预览结果
            // // // 参数依次为: 打开页面地址、标题、回调函数
            // openAppClient('/showSelectedData', 'kanbug', function () {
            //     // alert('关闭后回调')
            // })
            //更新基本信息字段
            //结算金额
            this.formData.settleAmount = this.jiesuanjine
            //税价合计
            this.formData.totalPrice = this.shuijiaheji
            //累计结算金额
            this.formData.totalSettleAmount = this.shuijiaheji
            await auditRequest.setjbxx({ ...this.formData })
            // alert('333')
            for(let i = 0 ; i < this.jsdwdata.length ; i++) {
                for(let j = 0 ;j < this.jsdwdata[i].children.length ; j++) {
                    if(this.jsdwdata[i].children[j].changeType != -1) {
                        this.jsdwdata[i].children[j].settleQuantity =   this.jsdwdata[i].children[j].settleQuantity - 0
                        this.jsdwdata[i].children[j].settleAmount = this.jsdwdata[i].children[j].settleAmount - 0
                        if(this.jsdwdata[i].children[j].changeType == 999) {
                            this.jsdwdata[i].children[j].changeType = 1
                        }else if(this.jsdwdata[i].children[j].changeType == 0 ) {
                            this.jsdwdata[i].children[j].changeType = 2
                        }
                    }
                }
            }
            // alert('22222')
            // this.setSelectedInfo(this.jsdwdata)
            // // // 客户端弹窗预览结果
            // // // 参数依次为: 打开页面地址、标题、回调函数
            // openAppClient('/showSelectedData', '选择结果', function () {
            //     // alert('关闭后回调')
            // })
            await auditRequest.updatejxmx(this.jsdwdata)
            this.clientPop('suc', '保存成功')
            location.reload()
        },
        //保存
        submit () {
            this.$refs.rulesBase.validate(valid => {
                console.log('gg', valid)
                if (valid) {
                    this.thesubimt0()
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
            // alert('111')

        },
        async theState () {
            showLoading()
            await auditRequest.setjbxx(this.formData)
            for(let i = 0 ; i < this.jsdwdata.length ; i++) {
                for(let j = 0 ;j < this.jsdwdata[i].children.length ; j++) {
                    if(this.jsdwdata[i].children[j].changeType != -1) {
                        if(this.jsdwdata[i].children[j].changeType == 999) {
                            this.jsdwdata[i].children[j].changeType = 1
                        }else if(this.jsdwdata[i].children[j].changeType == 0 ) {
                            this.jsdwdata[i].children[j].changeType = 2
                        }
                    }
                }
            }
            await auditRequest.updatejxmx(this.jsdwdata)
            await auditRequest.tijiaoshenhe({
                'billId': this.$route.query.billid,
                'billType': 6097,
                'freeNextUnitIndex': 0,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': ''
            })
            hideLoading()
            this.clientPop('suc', '提交成功')
            this.$router.replace('/peripheralMaterialList')
        },
        //取消
        handleClose () {
            hideLoading()
            this.$router.replace('/peripheralMaterialList')
        },
        tableRowClassName ({ row }) {
            if(row.changeType === -1) {
                if(row.hasChildren) {
                    return `class-${row.billId} row-hide`
                }else{
                    return `class-${row.billId}  row-hide hide-icon`
                }
            }else{
                if(row.hasChildren) {
                    return `class-${row.billId} row-show`
                }else{
                    return `class-${row.billId}  row-show hide-icon`
                }
            }
        },
        //查看源单页面
        seeSourceOrder () {
            openAppClient(
            `/revolveAllocationShow?billid=${this.formData.sourceId}&isview=true`, '查看周材调拨单'
            )
        },
        //税率事件
        taxRateEvent (val) {
            if(val < 0 || val > 100) {
                this.$message.error('税率的有效值为0~100')
                this.formData.taxRate = 0
            } else {
                this.formData.taxRate = Number(val).toFixed(2) * 1
            }
            this.formData.taxAmount = (this.jiesuanjine * (this.formData.taxRate / 100)).toFixed(2) * 1
        }
    }
}
</script>

<style lang="scss" scoped>
.mainTitle {
    box-sizing: border-box;
    width: 100%;
    height: 40px;
    line-height: 40px;
    background: rgb(246, 246, 246);
    border: 1px solid rgb(236, 236, 236);
    margin: auto;
    margin-bottom: 15px;
    padding-left: 10px;
}
.e-table {
    min-height: auto;
    background: #fff;
}
.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep.el-input--suffix .el-input__inner {
    padding-right: 5px;
}
::v-deep.el-table .cell {
    text-align: center;
}

.lll{
    width: 100%;
    height: 30px;
    line-height: 30px;
    background: #F2F2F2;
    padding-right: 20px;
    padding-left: 20px;
}
.buttons {
  left: 0;
}
.e-form {
  margin-bottom: 80px;
  padding: 0 20px;
  .tabs-title::before {
    content: "";
    height: 22px;
    width: 8px;
    border-radius: 40px;
    background-color: #2e61d7;
    display: block;
    position: absolute;
    left: 20px;
    margin-right: 20px;
  }
}

.e-table {
  background: #fff;
}
::v-deep.el-table .warning-row {
  display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 5px;
}
::v-deep.el-table .warning-row {
    display: none;
}
.el-tab-pane {
  margin-left: -10px;
}
.childTab {
  ::v-deep .el-tabs__header {
    position: absolute !important;
  }
  ::v-deep .el-tabs__content {
    padding: 0 0 0 20px !important;
  }
}
.childTab1 {
  ::v-deep .el-tabs__header {
    position: absolute !important;
    .el-tabs__nav-scroll {
      position: relative;
      .el-tabs__nav {
        position: fixed;
        top: 0;
        width: 190px;
      }
    }
  }
}
.childTab2 {
  ::v-deep .el-tabs__header {
    position: absolute !important;
    .el-tabs__nav-scroll {
      position: relative;
      .el-tabs__nav {
        position: absolute;
        bottom: 0;
        width: 100%;
      }
    }
  }
}
</style>